﻿(function ($) {
    $.fn.yqForeignKey = function (opts, param) {
        if (typeof opts == 'string') {
            return $.fn.yqForeignKey.methods[opts](this, param);
        }

        return this.each(function () {
            var $this = $(this);
            var opt;
            if ($this.data("yqtype") == "yqForeignKey") {
                var $uniqueID = $this.attr("ID");
                var opts_ = $.extend({}, options($this));
                destroy($this);
                $this = $("#" + $uniqueID);
                opt = $.extend(opts_, opts);
            }
            else {
                opt = $.extend({}, $.fn.yqForeignKey.defaults, opts);
                var $uniqueID = $this.attr("ID");
                if ($uniqueID === undefined || $uniqueID === null || $uniqueID == "") {
                    $uniqueID = $.getUniqueID();
                    $this.attr("ID", $uniqueID);
                }
            }

            $this.html("");

            if (opt.width === undefined) {
                opt.width = $this.width();
            }

            opt.prewhere = "*";
            if (opt.row === undefined || opt.row === null) {
                opt.row = {};
            }

            //组件加载结束
            opt.onload = true;
            //组件进程执行中
            opt.running = false;

            opt.firstShowPanel = false;

            //变量信息
            $this.data("foreignkey_opt", opt);
            $this.data("yqtype", "yqForeignKey");

            if (opt.displayType == 2) {
                opt.row = {};
            }

            initui($this);
        });
    };

    $.fn.yqForeignKey.defaults = {
        ajaxUrl: "/_db.html", //ajax地址

        //width: 200,
        panelWidth: 600,
        panelHeight: 280,

        displayType: 2,                 //显示类型, 1--下拉列表 2--查询窗体
        dbname: "yqbase",               //数据库
        tbname: "",                     //表
        tempno: 100,                    //实例 
        addWhere: "",                   //额外条件
        order: "",                     //排序

        isPage: true,                   //分页
        pageSize: 10,
        pageNo: 1,
        pageList: [5, 10, 20, 30, 40, 50],

        valueMember: "sid",             //值字段
        displayMember: "sid",          //显示字段

        titles: [],                     //数据列配置对象

        expandMember: null,              //扩展查询字段,用“,”分割（用于下拉列表模式）

        isSeek: true,                    //弹窗查询
        seekNo: -1,                      //查询模板编码  displayType=2生效
        seekModeW: 500,                  //模态编辑器宽度 格式为 800（数字）
        seekModeH: 350,                  //模态编辑器高度 格式为 600（数字）
        //用于查询窗体
        seekSimple: true,     //简单查询
        seekSimpleDDLW: 150,  //条件宽度
        seekSimpleTxtW: 200,  //条件宽度

        enable: true,                    //是否可用，默认可用

        beforeBindingTitle: function (columns, callback) {
            callback(columns);
        },

        onClickRow: function (rowIndex, rowData) { },  //选择行事件 null：为空
    };

    $.fn.yqForeignKey.methods = {
        options: function (jq) {
            return options($(jq[0]));
        },
        destroy: function (jq) {
            destroy($(jq[0]));
        },
        disable: function (jq) {
            enable($(jq[0]), false);
        },
        enable: function (jq) {
            enable($(jq[0]), true);
        },
        addWhere: function (jq, value) {
            options($(jq[0])).addWhere = value;
        },
        setValue: function (jq, value) {
            setValue($(jq[0]), value);
        },
        getValue: function (jq) {
            return getValue($(jq[0]));
        },
        setRow: function (jq, row) {
            setRow($(jq[0]), row);
        },
        getRow: function (jq) {
            return getRow($(jq[0]));
        },
        clear: function (jq) {
            var $object = $(jq[0]);
            var o = options($object);
            options($object).where = "@*@";

            // $object.combogrid("clear");
            // o.onClickRow.call($object, -1, null);

            setValue($object, null);
        },
        resize: function (jq, width) {
            resize($(jq[0]), width);
        }
    };

    function options($object) {
        return $object.data("foreignkey_opt");
    }

    function resize($object, width) {
        var opt = options($object);

        if (opt === undefined) {
            $object.width(width);
        }
        else {
            if (opt.displayType == 1) {
                $object.combogrid("resize", width);
            }
            else {
                $object.textbox("resize", width);
            }
        }

        enable($object, opt.enable);
    }

    function destroy($object) {
        var opt = options($object);
        var $new_obj = $($object.prop("outerHTML"));
        $new_obj.show();
        var id = $object.attr("id");
        $new_obj.removeAttr("id");
        $new_obj.removeClass("textbox-f");
        $new_obj.removeClass("combo-f");
        $new_obj.removeClass("combogrid-f");
        $object.before($new_obj);

        if (opt.displayType == 1) {
            $object.combogrid("destroy");
        } else {
            $object.textbox("destroy");
        }

        $new_obj.attr("id", id);

        $object.removeData("foreignkey_opt");
        $object.removeData("yqtype");
    }

    function enable($object, tf) {
        var opt = options($object);

        opt.enable = tf;

        var $text = $object.next().find(".textbox-text");

        var btn_mub = 3;
        if (opt.displayType == 1) {
            var $icon0 = $object.combogrid("getIcon", 0);
            var $icon1 = $object.combogrid("getIcon", 1);
            var $icon2 = $object.combogrid("getIcon", 2);
            if (opt.enable) {
                if (opt.isSeek) {
                    $icon1.show();
                    btn_mub = 3;
                } else {
                    $icon1.hide();
                    btn_mub = 2;
                }
                $icon2.show();
                $object.combogrid("enable");
            } else {
                $icon1.hide();
                $icon2.hide();
                $object.combogrid("disable");
                btn_mub = 1;
            }
        } else {
            var $icon0 = $object.textbox("getIcon", 0);
            var $icon1 = $object.textbox("getIcon", 1);
            if (opt.enable) {
                $icon0.show();
                $icon1.show();

                btn_mub = 2;
            } else {
                $icon0.hide();
                $icon1.hide();
                btn_mub = 0;
            }

            if (opt.enable) {
                $text.removeAttr("disabled");
            } else {
                $text.attr("disabled", "true");
            }
        }

        opt.width = $object.next().width();
        $text.css({
            "margin": "0px " + (26 * btn_mub) + "px 0px 0px",
            "width": (opt.width - (26 * btn_mub)) + "px"
        });
    }

    function initui($object) {
        var opt = options($object);
        if (opt.displayType == 1) {
            var opt_dg = {
                width: opt.width,
                fitColumns: false,
                striped: true,

                collapsible: false,
                idField: opt.valueMember,
                textField: opt.displayMember,

                rownumbers: true,
                singleSelect: true,

                columns: [[
                    { field: opt.valueMember, title: 'ID', width: 80 },
                    { field: opt.displayMember, title: 'Name', width: 200 }
                ]],
                data: [],
                icons: [{
                    iconCls: 'icon-clear',
                    handler: function (e) {                       
                        $object.combogrid("clear");
                    }
                }, {
                    iconCls: 'icon-search',
                    handler: function (e) {
                        if (!(opt.error === undefined)) {
                            return;
                        }

                        e.preventDefault();

                        if (opt.toolbar === undefined) {
                            var pp_opt = {
                                ajaxUrl: opt.ajaxUrl,
                                dbname: opt.dbname,                //数据库
                                tbname: opt.tbname,                //表
                                tempno: opt.tempno
                            };

                            $.yqTbTitle(pp_opt, function (res) {
                                if (res.error == 0) {
                                    opt.titles = res.titles;
                                    opt.toolbar = $("<div></div>");
                                    var menu_opt = {
                                        type: 4,  //1(!=2或3)-顶部菜单，2-右键菜单，3-顶部+右键
                                        titles: opt.titles,         //
                                        isSeek: opt.isSeek,  //高级查询
                                        seekModeW: opt.seekModeW,
                                        seekModeH: opt.seekModeH,
                                        onSeek: function (where, order) {           //查询
                                            opt.order = order;
                                            seek($object, where);
                                        }
                                    };
                                    opt.toolbar.yqEditMenu(menu_opt);

                                    opt.toolbar.yqEditMenu("open_seek", $object.combogrid("textbox"));
                                }
                                else {
                                    opt.error = {
                                        error: res.error,
                                        info: res.info,
                                    }
                                }
                            })
                        } else {
                            opt.toolbar.yqEditMenu("open_seek", $object.combogrid("textbox"));
                        }
                    }
                }],
                onChange: function (newValue, oldValue) {
                    if (!opt.onload && !opt.running) {
                        var rowIndex = -1;
                        var rowData = $(this).combogrid('grid').datagrid('getSelected');
                        if (!(rowData === null)) {
                            rowIndex = $(this).combogrid('grid').datagrid('getRowIndex', rowData);
                        }

                        opt.onClickRow.call($(this), rowIndex, rowData);
                    }
                },
                onLoadSuccess: function (data) {
                    get_columns($object);
                },
                editable: true,
                keyHandler: {
                    enter: function () {
                        if (opt.onload) {
                            return;
                        }

                        var q = $(this).combogrid("getText");
                        if (q === null || q == "") {
                            q = "*";
                        }

                        keyHandler_seek($(this), q);
                    },
                    up: function () { },
                    down: function () { },
                    left: function () { },
                    right: function () { },
                    query: function (q) { }
                },
                onShowPanel: function () {
                    try {
                        if (opt.onload) {
                            return;
                        }

                        if (!(opt.error === undefined)) {
                            return;
                        }

                        if (!opt.firstShowPanel) {
                            opt.firstShowPanel = true;
                            var rowData = $(this).combogrid('grid').datagrid('getSelected');
                            if (rowData === null) {
                                var q = $(this).combogrid("getText");
                                if (q === null || q == "") {
                                    q = "*";
                                }

                                keyHandler_seek($(this), q);
                            }
                        }
                    }
                    catch (Error) {
                        alert(Error);
                    }
                },
            };

            if (typeof opt.panelWidth != undefined) {
                opt_dg.panelWidth = opt.panelWidth;
            }
            if (typeof opt.panelHeight != undefined) {
                opt_dg.panelHeight = opt.panelHeight;
            }


            if (opt.isPage) {
                opt_dg.pagination = true;  //显示分页
                opt_dg.pageNumber = opt.pageNo;
                opt_dg.pageSize = opt.pageSize;
                opt_dg.pageList = opt.pageList;
            }

            $object.combogrid(opt_dg);
        } else {
            var opt_txt = {
                width: opt.width,
                icons: [{
                    iconCls: 'icon-clear',
                    handler: function (e) {
                        opt.row = null;
                        $(e.data.target).textbox("setValue", "");

                        opt.onClickRow.call($object, -1, null);
                    }
                }, {
                    iconCls: 'icon2-down',
                    handler: function (e) {
                        get_select($object);
                    }
                }]
            }

            $object.textbox(opt_txt);
            $object.next().find(".textbox-text").attr("readonly", true);

            opt.onload = false;

            $object.textbox("options").onResize = function (width, height) {
                opt.width = width;
                enable($object, opt.enable);
            };
        }

        enable($object, opt.enable);
    }

    //-- begin displayType=1 -----------------------------------------------
    function get_columns($object) {
        var opt = options($object);

        if (opt.titles.length > 0) {
            set_columns($object);
        } else {
            var pp_opt = {
                ajaxUrl: opt.ajaxUrl,
                dbname: opt.dbname,                //数据库
                tbname: opt.tbname,                //表
                tempno: opt.tempno
            };

            $.yqTbTitle(pp_opt, function (res) {
                if (res.error == 0) {
                    opt.titles = res.titles;
                    set_columns($object);
                }
                else {
                    opt.error = {
                        error: res.error,
                        info: res.info,
                    }
                }
            })
        }

    }

    function set_columns($object) {
        var opt = options($object);
        opt.titles = $.yqFmUiTitle(opt.titles);
        var columns = $.yqDgColumns.call($object, opt.titles);
        opt.beforeBindingTitle.call($object, columns, function (columns_) {
            opt.columns = columns_;

            var opt_dg = {
                "columns": columns_,
                onLoadSuccess: function (data) {
                }
            };

            $object.combogrid("grid").datagrid(opt_dg);

            $object.combogrid("grid").datagrid("options").onLoadSuccess = function (data) {
                opt.running = false;
                $object.combogrid("grid").datagrid("loaded");

                if (opt.isPage) {
                    var pager = $(this).datagrid('getPager');
                    pager.pagination('refresh', {
                        total: data.recordCount,    //;
                        pageNumber: data.pageNo
                    });
                }
            };

            if (opt.isPage) {
                var $pager = $object.combogrid("grid").datagrid('getPager');
                $pager.pagination({
                    onSelectPage: function (pageNo, pageSize) {
                        opt.pageSize = pageSize;
                        opt.pageNo = pageNo;
                        //console.log(pageNo, pageSize);
                        loadData($object, opt.prewhere);
                    }
                });
            }

            var $icon0 = $object.combogrid("getIcon", 0);
            var $icon3 = $object.combogrid("getIcon", 2);
            $icon0.before($icon3);

            opt.onload = false;
        });
    }

    function keyHandler_seek($object, q) {
        var opt = options($object);

        if (opt.running) {
            return;
        }

        console.log("q", q);

        var opt = options($object);
        var where = "";
        if (q != "*") {
            where = "(" + opt.displayMember + " like '%" + q + "%'";
            if (!(opt.expandMember === null)) {
                var extlist = opt.expandMember.split(",");
                if (extlist.length > 0) {
                    for (var ii = 0; ii < extlist.length; ii++) {
                        where = where + " or " + extlist[ii] + " like '%" + q + "%'";
                    }
                }
                else {
                    where = where + " or " + opt.expandMember + " like '%" + q + "%'";
                }
            }

            where = where + ")";
        }

        seek($object, where);
    }

    function seek($object, where) {
        var opt = options($object);

        if (opt.running) {
            return;
        }
        if (where == opt.prewhere) {
            return;
        }
        loadData($object, where);
    }

    //加载数据
    function loadData($object, where, callback) {
        var opt = options($object);

        opt.running = true;

        if (where === null) {
            where = "";
        }

        if (!opt.isSeek) {
            where = "";
        }

        opt.prewhere = opt.where;
        var l_where = where;
        if (!(opt.addWhere === null) && opt.addWhere != "") {
            if (l_where == "") {
                l_where = opt.addWhere;
            } else {
                l_where = "(" + l_where + ") and (" + opt.addWhere + ")";
            }
        }

        $object.combogrid("grid").datagrid("loading");

        if (opt.isPage) {
            $.yqDbTbPaging({
                url: opt.ajaxUrl,
                dbname: opt.dbname,
                tbname: opt.tbname,
                where: l_where,
                order: opt.order,
                pagesize: opt.pageSize,
                pageno: opt.pageNo
            }, function (data) {
                if (typeof callback == "function") {
                    callback(data);
                } else {
                    if (data.error == 0) {
                        toData($object, data)
                    }
                    else {
                        opt.running = false;
                        $object.combogrid("grid").datagrid("loaded");
                    }

                }
            });
        }
        else {
            $.yqDbTbSelect({
                url: opt.ajaxUrl,
                dbname: opt.dbname,
                tbname: opt.tbname,
                where: l_where,
                order: opt.order
            }, function (data) {
                if (typeof callback == "function") {
                    callback(data);
                } else {
                    if (data.error == 0) {
                        toData($object, data)
                    }
                    else {
                        opt.running = false;
                        $object.combogrid("grid").datagrid("loaded");
                    }
                }
            });
        }
    }

    function toData($object, data) {
        var opt = options($object);
        opt.running = true;
        $object.combogrid("grid").datagrid("loading");

        setForienKeys($object, data.rows,
            function () {
                $object.combogrid("grid").datagrid("loadData", data);
            });
    }

    function setForienKeys($object, rows, callback) {
        var opt = options($object);
        var opts = {
            "ajaxUrl": opt.ajaxUrl,
            "rows": rows,
            "titles": opt.titles,
            "fk_rows": opt.fk_rows === undefined ? [] : opt.fk_rows
        };

        $.yqGetForeignkeys(opts,
            function (fk_rows) {
                opt.fk_rows = fk_rows;
                callback();
            });
    }
    //-- end displayType=1 -----------------------------------------------

    function get_select($object) {
        var opt = options($object);

        if (!(opt.error === undefined)) {
            return;
        }

        var $txt = $object.next().find(".textbox-text");
        prevent_e = $.getPreventDefault($txt[0]);
        prevent_e.id = $object.attr("id");
        prevent_e.options = opt;

        var mdiinfo = $.yqGetWindParams();

        var run_opt = {
            ajaxUrl: opt.ajaxUrl,
            mdiinfo: mdiinfo,
            prevent_e: prevent_e,

            dbname: opt.dbname,                   //数据库
            tbname: opt.tbname,                   //表
            tempno: opt.tempno,                   //实例 
            addWhere: opt.addWhere,               //额外条件
            order: opt.order,                     //排序

            width: opt.panelWidth,
            height: opt.panelHeight,

            isPage: opt.isPage,                   //分页
            pageSize: opt.pageSize,
            pageNo: opt.pageNo,
            pageList: opt.pageList,

            seekSimple: opt.seekSimple,             //简单查询
            seekSimpleDDLW: opt.seekSimpleDDLW,     //条件宽度
            seekSimpleTxtW: opt.seekSimpleTxtW,     //条件宽度

            isSeek: opt.isSeek,
            seekNo: opt.seekNo,                     //查询模板编码  displayType=2生效
            seekModeW: opt.seekModeW,               //模态编辑器宽度 格式为 800（数字）
            seekModeH: opt.seekModeH,               //模态编辑器高度 格式为 600（数字）

            valueMember: opt.valueMember,             //值字段
            defaultValue: getValue($object),

            callback: function (row) {
                if (row != null) {
                    if ($object.data("yqtype") === undefined) {
                        var ed = $.yqTextEditor(opt.p_target, opt.p_field);
                        if (!(ed === null)) {
                            $(ed.target).yqForeignKey('setRow', row);
                            opt.onClickRow.call($(ed.target), 0, row);
                        }
                    } else {
                        setRow($object, row);
                        opt.onClickRow.call($object, 0, row);
                    }
                }
            },
        };
        if (window.top == window.self) {
            $.yqRowsPopSelect(run_opt);
        }
        else {
            window.top.$.yqRowsPopSelect(run_opt);
        }
    }

    function setValue($object, value) {
        var opt = options($object);

        if (!opt.onload) {
            setValueRun($object, value);
        }
        else {
            setTimeout(function () {
                setValue($object, value);
            }, 500);
        }

    }

    function setValueRun($object, value) {
        var opt = options($object);

        if (opt.displayType == 1) {
            var $d = $object.combogrid("grid");
            var rows = $d.datagrid("getRows");
            var hasitem = false;
            for (let i = 0; i < rows.length; i++) {
                if (rows[i][opt.valueMember] == value) {
                    hasitem = true;
                    break;
                }
            }

            if (hasitem) {
                $object.combogrid("setValue", value);
                return;
            }

            if (opt.isPage || opt.isSeek) {
                $.yqDbTbRow({
                    url: opt.ajaxUrl,
                    dbname: opt.dbname,
                    tbname: opt.tbname,
                    keyid: opt.valueMember,
                    keyval: value
                }, function (data) {
                    if (data.error == 0) {
                        if (!(data.row === null)) {
                            setForienKeys($object, [data.row],
                                function () {
                                    $d.datagrid("appendRow", $.yqFmToView(data.row, opt.titles));
                                    $object.combogrid("setValue", value);
                                });
                        }
                    } else {
                        opt.error = {
                            error: data.error,
                            info: data.info,
                        }
                    }
                });
            } else {
                loadData($object, "", function (data) {
                    if (data.error == 0) {
                        setForienKeys($object, data.rows,
                            function () {
                                $d.datagrid("loadData", $.yqFmToViews(data.rows, opt.titles));
                                $object.combogrid("setValue", value);
                            });
                    }
                });
            }
        } else {
            opt.row = null;
            opt.running = true;
            $object.textbox("setText", "");
            $.yqDbTbRow({
                url: opt.ajaxUrl,
                dbname: opt.dbname,
                tbname: opt.tbname,
                keyid: opt.valueMember,
                keyval: value
            }, function (data) {
                if (data.error == 0) {
                    opt.row = data.row;
                    var txt = $.getDisplayValue(opt.row, opt.displayMember);
                    $object.textbox("setText", txt);
                } else {
                    opt.error = {
                        error: data.error,
                        info: data.info,
                    }
                }

                opt.running = false;
            });
        }
    }

    function getValue($object) {
        var opt = options($object);
        if (opt.displayType == 1) {
            var val = $object.combogrid('getValue');
            if (val == "") {
                val = null;
            }

            return val;
        } else {
            if (opt.row === undefined || opt.row === null) {
                opt.row = {};
            }

            if (Object.getOwnPropertyNames(opt.row).length > 0) {
                return opt.row[opt.valueMember];
            } else {
                return null;
            }
        }
    }

    function setRow($object, row) {
        var opt = options($object);
        if (opt.displayType == 1) {
            if (row == null) {
                opt.row = {};
                $object.combogrid("clear");
                return;
            }

            var $d = $object.combogrid("grid");
            var rows = $d.datagrid("getRows");
            var hasitem = false;
            for (let i = 0; i < rows.length; i++) {
                if (rows[i][opt.valueMember] == row[opt.valueMember]) {
                    hasitem = true;
                    break;
                }
            }

            if (hasitem) {
                $object.combogrid("setValue", row[opt.valueMember]);
                return;
            }

            setForienKeys($object, [row],
                function () {
                    $d.datagrid("appendRow", $.yqFmToView(row, opt.titles));
                    $object.combogrid("setValue", value);
                });
        } else {
            opt.row = row;
            if (row == null) {
                $object.textbox("setText", "");
            } else {
                var txt = $.getDisplayValue(opt.row, opt.displayMember);
                $object.textbox("setText", txt);
            }
        }
    }

    function getRow($object) {
        var opt = options($object);
        if (opt.displayType == 1) {
            var $d = $object.combogrid("grid");
            return $d.datagrid("getSelected");
        } else {
            if (opt.row === undefined || opt.row === null) {
                return null;
            }

            if (Object.getOwnPropertyNames(opt.row).length > 0) {
                return opt.row;
            }
            else {
                return null;
            }
        }
    }

})(jQuery);